package com.nuoniu.sibanyun.service.crm.call.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nuoniu.sibanyun.common.BaseEntity;
import com.nuoniu.sibanyun.common.exception.NuoNiuException;
import com.nuoniu.sibanyun.common.lang.StringUtils;
import com.nuoniu.sibanyun.entity.crm.CrmLinkman;
import com.nuoniu.sibanyun.entity.crm.CrmStrategy;
import com.nuoniu.sibanyun.entity.crm.call.CrmCallTask;
import com.nuoniu.sibanyun.entity.crm.call.CrmCallTaskDetail;
import com.nuoniu.sibanyun.entity.crm.call.dto.CrmCallTaskDetailSaveDto;
import com.nuoniu.sibanyun.entity.crm.call.dto.CrmCallTaskDetailSearchDto;
import com.nuoniu.sibanyun.entity.crm.call.dto.CrmCallTaskDetailUpdateDto;
import com.nuoniu.sibanyun.entity.crm.call.dto.CrmCallTaskUpdateDto;
import com.nuoniu.sibanyun.mapper.crm.call.CrmCallTaskDetailMapper;
import com.nuoniu.sibanyun.service.crm.ICrmCustomerService;
import com.nuoniu.sibanyun.service.crm.ICrmLinkmanService;
import com.nuoniu.sibanyun.service.crm.ICrmStrategyService;
import com.nuoniu.sibanyun.service.crm.call.ICrmCallTaskDetailService;
import com.nuoniu.sibanyun.service.crm.call.ICrmCallTaskService;
import com.nuoniu.sibanyun.userThread.UserInfo;
import com.nuoniu.sibanyun.userThread.UserThreadLocal;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 客户管理-外呼管理-外呼任务明细 服务实现类
 * </p>
 *
 * @author 白强
 * @since 2022-03-03
 */
@Service
@Log4j2
public class CrmCallTaskDetailServiceImpl extends ServiceImpl<CrmCallTaskDetailMapper, CrmCallTaskDetail> implements ICrmCallTaskDetailService {

    /** 校验 数字 用逗号 隔开 的字符串 */
    private static final String STR_ENG_PATTERN="^\\d+(,\\d+)*$";
    @Autowired
    private ICrmCallTaskService taskService;
    @Autowired
    private ICrmCustomerService customerService;
    @Autowired
    private ICrmLinkmanService linkmanService;
    @Autowired
    private ICrmStrategyService crmStrategyService;

    @Override
    public List<CrmCallTaskDetail> listTaskDetail(CrmCallTaskDetailSearchDto crmCallTaskDetailSearchDto) {
        UserInfo userInfo = UserThreadLocal.get();
        List<CrmCallTaskDetail> list = baseMapper.listTaskDetail(userInfo.getCompanyId(), crmCallTaskDetailSearchDto);
        return list;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void addCallTaskDetail(CrmCallTaskDetailSaveDto crmCallTaskDetailSaveDto) {
        UserInfo userInfo = UserThreadLocal.get();
        Integer userId = userInfo.getUserId();
        String realName = userInfo.getRealName();
        LocalDateTime now = LocalDateTime.now();
        Long taskId = crmCallTaskDetailSaveDto.getTaskId();
        CrmCallTask callTask = taskService.detailById(taskId);
        if(null == callTask)throw new NuoNiuException("查询不到任务");
        if(callTask.getBusinessStatus() > 0)throw new NuoNiuException("任务已经关闭，不能添加");
        List<CrmCallTaskDetail> crmCallTaskDetailList = crmCallTaskDetailSaveDto.getCrmCallTaskDetailList();
        if(null == crmCallTaskDetailList || crmCallTaskDetailList.size() == 0)throw new NuoNiuException("请选择联系人");
        Set<Long> crmIds = new LinkedHashSet<>();
        Set<Long> linkManIds = new LinkedHashSet<>();
        //检查是否开启 线索客户 脱敏策略 1可见 0 不可见
        CrmStrategy crm9 = crmStrategyService.getStrategyByCode("crm_9", userInfo.getCompanyId());
        boolean isSelectMobile = false;
        Map<String,String> mobileMap = new HashMap<>();
        if(null != crm9 && crm9.getStrategyVal().equals("0") ){
            isSelectMobile = true;
            //查询联系人 电话
            List<CrmLinkman> crmLinkmen = linkmanService.listCrmLinkmanMobile(crmCallTaskDetailList.stream().map(CrmCallTaskDetail::getLinkManId).collect(Collectors.toList()));
            if(crmLinkmen.size() > 0){
                crmLinkmen.forEach(f->mobileMap.put(f.getId().toString(),f.getMobile()));
            }

        }
        for (int i = 0; i < crmCallTaskDetailList.size() ; i++) {
            CrmCallTaskDetail item = crmCallTaskDetailList.get(i);
            if(null == item.getLinkManId())throw new NuoNiuException("联系人错误");
            item.setCompanyId(callTask.getCompanyId());
            item.setCrmCallTaskId(callTask.getId().intValue());
            item.setCrmCallTaskName(callTask.getTaskName());
            item.setAddTime(now);
            item.setCreateUserId(userId);
            item.setCreateUserName(realName);
            crmIds.add(item.getCrmId().longValue());
            linkManIds.add(item.getLinkManId().longValue());
            if(isSelectMobile && null != item.getLinkManId()){
                String mobile = mobileMap.get(item.getLinkManId().toString());
                if(StringUtils.isNotBlank(mobile)){
                    item.setMobile(mobile);
                }
            }
        }
        this.saveOrUpdateBatch(crmCallTaskDetailList);
        /** 更新 客户外呼状态 */
        customerService.updateCallTaskState(userInfo,crmIds,callTask.getId().intValue(),true);
        /** 更新 联系人外呼状态 */
        linkmanService.updateCallTaskState(userInfo,linkManIds,taskId.intValue(),true);
        /** 更新 任务的统计数据*/
        CrmCallTaskUpdateDto callTaskUpdateDto = new CrmCallTaskUpdateDto();
        callTaskUpdateDto.setCompanyId(userInfo.getCompanyId());
        callTaskUpdateDto.setCrmCallTaskId(taskId.intValue());
        callTaskUpdateDto.setMobileCount(crmCallTaskDetailList.size());
        taskService.updateTaskMobileCount(callTaskUpdateDto);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void andCallTaskDetailFromImportCrmCustomer(UserInfo userInfo,Long taskId, Collection<CrmLinkman> crmLinkmanList) {
        Integer userId = userInfo.getUserId();
        String realName = userInfo.getRealName();
        LocalDateTime now = LocalDateTime.now();
        log.info("1.外呼任务明细导入数据_任务ID：{},导入联系人数量：{}",taskId,crmLinkmanList.size());
        CrmCallTask callTask = taskService.detailById(taskId);
        if(null == callTask)throw new NuoNiuException("查询不到任务");
        if(callTask.getBusinessStatus() > 0)throw new NuoNiuException("任务已经关闭，不能添加");
        List<CrmCallTaskDetail> crmCallTaskDetailList = new ArrayList<>();
        Set<Long> crmIds = new LinkedHashSet<>();
        Set<Long> linkManIds = new LinkedHashSet<>();
        crmLinkmanList.forEach(item->{
            CrmCallTaskDetail detail = new CrmCallTaskDetail();
            detail.setCompanyId(callTask.getCompanyId());
            detail.setCrmCallTaskId(callTask.getId().intValue());
            detail.setCrmCallTaskName(callTask.getTaskName());
            detail.setAddTime(now);
            detail.setCreateUserId(userId);
            detail.setCreateUserName(realName);
            detail.setCrmId(item.getCrmId());
            detail.setCrmName(item.getCrmName());
            detail.setLinkManId(item.getId().intValue());
            detail.setLinkManName(item.getName());
            detail.setMobile(item.getMobile());
            detail.setOfficePhone(item.getOfficePhone());
            detail.setGender(item.getGender());
            crmCallTaskDetailList.add(detail);
            crmIds.add(item.getCrmId().longValue());
            linkManIds.add(item.getId());
        });
        boolean b = this.saveBatch(crmCallTaskDetailList);
        /** 更新 客户外呼状态 */
        customerService.updateCallTaskState(userInfo,crmIds,callTask.getId().intValue(),true);
        /** 更新 联系人外呼状态 */
        linkmanService.updateCallTaskState(userInfo,linkManIds,taskId.intValue(),true);
        /** 更新 任务的统计数据*/
        CrmCallTaskUpdateDto callTaskUpdateDto = new CrmCallTaskUpdateDto();
        callTaskUpdateDto.setCompanyId(userInfo.getCompanyId());
        callTaskUpdateDto.setCrmCallTaskId(taskId.intValue());
        callTaskUpdateDto.setMobileCount(crmCallTaskDetailList.size());
        taskService.updateTaskMobileCount(callTaskUpdateDto);
        log.info("2.外呼任务明细导入数据{}",b ? "成功":"失败");
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void batchDelete(Long taskId, String ids) {
        UserInfo userInfo = UserThreadLocal.get();
        if(null == taskId)throw new NuoNiuException("参数错误");
        if(StringUtils.isBlank(ids))throw new NuoNiuException("请选择记录");
        if(!ids.matches(STR_ENG_PATTERN))throw new NuoNiuException("参数错误");
        Set<Long> crmIds = baseMapper.listCrmIds(userInfo.getCompanyId(), taskId, ids);
        Set<Long> linkManIds = baseMapper.listLinkManIds(userInfo.getCompanyId(), taskId, ids);
        int batchDeleteNum = baseMapper.batchDelete(userInfo.getCompanyId(), taskId, ids);
        /** 更新 联系人外呼状态 */
        linkmanService.updateCallTaskState(userInfo,linkManIds,taskId.intValue(),false);
        /** 更新 客户外呼状态 */
        customerService.updateCallTaskState(userInfo,crmIds,taskId.intValue(),false);
        /** 更新 任务的统计数据*/
        CrmCallTaskUpdateDto callTaskUpdateDto = new CrmCallTaskUpdateDto();
        callTaskUpdateDto.setCompanyId(userInfo.getCompanyId());
        callTaskUpdateDto.setCrmCallTaskId(taskId.intValue());
        callTaskUpdateDto.setMobileCount(-batchDeleteNum);
        taskService.updateTaskMobileCount(callTaskUpdateDto);
}

    @Override
    public void updateDetailSateAndCount(CrmCallTaskDetailUpdateDto crmCallTaskDetailUpdateDto) {
        Long crmCallTaskDetailId = crmCallTaskDetailUpdateDto.getCrmCallTaskDetailId();
        Integer lastCallResult = crmCallTaskDetailUpdateDto.getLastCallResult();
        Boolean lastCallStatus = crmCallTaskDetailUpdateDto.getLastCallStatus();
        Integer companyId = crmCallTaskDetailUpdateDto.getCompanyId();
        if(null == companyId || null == crmCallTaskDetailId ||  null == lastCallStatus){
            log.info("更新任务明细拨打状态，companyId：{}，crmCallTaskDetailId：{}，lastCallResult：{}，上次拨打状态：lastCallStatus：{}",companyId,crmCallTaskDetailId,lastCallResult,lastCallStatus);
            return;
        }
        baseMapper.updateDetailSateAndCount(crmCallTaskDetailUpdateDto);

    }

    /**
     * 任务明细数量
     * @param taskIds
     * @return
     */
    @Override
    public Integer detailNum(List<Long> taskIds) {
        if(null == taskIds || taskIds.size() == 0)return null;
        QueryWrapper<CrmCallTaskDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("crm_call_task_id",taskIds);
        int count = count(queryWrapper);
        return count;
    }


}
